<?php
/**
 * 短信验证码
 */
namespace Home\Controller;
use Think\Controller;
use Common\Support\Curl;
use think\Log;
class SmsController extends Controller {

	/**
	 * 发送验证码
	 */
	public function sendSms(){

		$phone    = I('post.phone', '', 'trim');
        $type     = I('post.type', '1', 'trim');
        if(!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/",$phone)){
            $this->ajaxReturn(['status' => false, 'code'=>1001,'msg' => '手机号错误']);
        }

        /*if($type == ''){
            $this->ajaxReturn(['status' => false, 'code'=>1002,'msg' => '短信类别不能为空']);
        }

        if($type == 'register'){
            //一个手机号既能注册商户，也能注册成客户
            if(M('seller')->where(['phone'=>$phone])->find() && M('user')->where(['phone'=>$phone])->find()){
                $this->ajaxReturn(['status' => false, 'code'=>1003,'msg' => '手机号已注册']);
            }
        }*/

        $response = Sms::sendCode($mobile);
        
        if($response->Message == 'OK'){
            $arr = [
                'phone'=>$phone,
                'code' =>$res['data'],
                'result' => 'OK',
                'create_time' =>time(),
            ];
            M('sms_code')->add($arr);

            $this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '短信发送成功','data'=>['phone'=>$phone,'num'=>$res['data']]]);
        }else{
            $arr = [
                'phone'=>$phone,
                'code' =>$res['data'],
                'result' => $response->Message,
                'create_time' =>time(),
           ];
            M('sms_code')->add($arr);
            $this->ajaxReturn(['status' => false, 'code'=>1004,'msg' => '短信发送失败']);
        }
        
	}

	private function send($phone){

	    $pool='0123456789';
        $rand_key='';
        for($i = 0;$i < 6;$i++){
            $rand_key.=substr($pool, mt_rand(0,  strlen($pool)-1),1);
        }

        $data = [
			'mobile'   => $phone,
			'account'  => $this->_account,
			'password' => $this->_password,
			'content'  => "您的验证码是：".$rand_key."。请不要把验证码泄露给其他人。",
		];

        $res = Curl::post($this->_url,$data);
        if(strstr($res,'提交成功')){
            S($phone,$rand_key,600);
            return ['code'=>1000,'data'=>$rand_key];
        }else{
            return ['code'=>1001,'data'=>$res];
        }
	}

    public function test(){
        $phone = '18672197927';
        $data = [
            'mobile'   => $phone,
            'account'  => $this->_account,
            'password' => $this->_password,
            'content'  => "欢迎您提交资料，申请入驻自然贝商户。您的审核暂未通过！请及时修改申请资料，重新提交。",
        ];

        $res = Curl::post($this->_url,$data);

        var_dump($res);
        exit();
        if(strstr($res,'提交成功')){
            //S($phone,$rand_key,600);
            return ['code'=>1000,'data'=>$rand_key];
        }else{
            return ['code'=>1001,'data'=>$res];
        }
    }
}